//
//  RightSideViewController.swift
//  CJXSwiftStoryboard
//
//  Created by CJX on 2016/10/20.
//  Copyright © 2016年 caijianxi. All rights reserved.
//

import UIKit
import SVProgressHUD
import SwiftyJSON

//protocol RightSideViewControllerDelegate {
//    func letMainVCGoToNextVC(index:Int)
//}

class RightSideViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,LoginViewControllerDelegate {
  
//    var delegate : RightSideViewControllerDelegate?
    
    var shoppingCount : String = "0"
    var wishListCount : String = "0"
    var orderCount : String = "0"
    
    var shoppongCountLabel = UILabel()
    var wishlistCountLabel = UILabel()
    var orderCountLabel = UILabel()
    
    
    
    let RIGHTCELL = "RightCell"
    
    var myTableView = UITableView(frame: CGRectMake(0, 20, SCREEN_WIDTH*0.75, SCREEN_HEIGHT-20), style: .Grouped)
    
    let imageViewArray = ["rightbar_shopping",
                           "rightbar_wish_list",
                            "rightbar_shopping",
                             "rightbar_store",
                              "rightbar_newsletter",
                               "right_Return",
                                "right_Pricvacy",
                                 "right_Shipping",
                                  "rightbar_cancellation"]
    let titleArray = ["SHOPPING",
                       "WISH LIST",
                        "ORDER",
                         "CURRENCY",
                          "CONTACT",
                           "RETURN POLICY",
                            "PRICVACY POLICY",
                             "SHIPPING POLICY",
                              "CANCELLATION"]
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.automaticallyAdjustsScrollViewInsets = false
        self.navigationController?.navigationBar.hidden = true
        self.creatCountView()
        self.creatTableView()
        self.getCountData()
        
        let center = NSNotificationCenter.defaultCenter()
        center.addObserver(self, selector: #selector(self.letRightVCRefresh), name: "RightVCRefreshed", object: nil)
        
    }
    
    
}
extension RightSideViewController{
    private func creatCountView(){
        shoppongCountLabel.frame = CGRectMake(SCREEN_WIDTH*0.75-45, SCREEN_HEIGHT*0.04-12.5, 25, 25)
        shoppongCountLabel.layer.cornerRadius = 12.5
        shoppongCountLabel.layer.masksToBounds = true
        shoppongCountLabel.backgroundColor = UIColor(red: 241/255.0, green: 42/255.0, blue: 44/255.0, alpha: 1)
        shoppongCountLabel.textColor = UIColor.whiteColor()
        shoppongCountLabel.font = UIFont.systemFontOfSize(13)
        shoppongCountLabel.textAlignment = .Center
        
        wishlistCountLabel.frame = CGRectMake(SCREEN_WIDTH*0.75-45, SCREEN_HEIGHT*0.04-12.5, 25, 25)
        wishlistCountLabel.layer.cornerRadius = 12.5
        wishlistCountLabel.layer.masksToBounds = true
        wishlistCountLabel.backgroundColor = UIColor(red: 241/255.0, green: 42/255.0, blue: 44/255.0, alpha: 1)
        wishlistCountLabel.textColor = UIColor.whiteColor()
        wishlistCountLabel.font = UIFont.systemFontOfSize(13)
        wishlistCountLabel.textAlignment = .Center
        
        orderCountLabel.frame = CGRectMake(SCREEN_WIDTH*0.75-45, SCREEN_HEIGHT*0.04-12.5, 25, 25)
        orderCountLabel.layer.cornerRadius = 12.5
        orderCountLabel.layer.masksToBounds = true
        orderCountLabel.backgroundColor = UIColor(red: 241/255.0, green: 42/255.0, blue: 44/255.0, alpha: 1)
        orderCountLabel.textColor = UIColor.whiteColor()
        orderCountLabel.font = UIFont.systemFontOfSize(13)
        orderCountLabel.textAlignment = .Center
        
    }
}

extension RightSideViewController{
    
    private func getCountData(){
        
        
        if UserSession.shareInstance.cookie != nil {
            
            
            //        shopping

            let parma1 = ["main_page":"shopping_cart","zendid":UserSession.shareInstance.cookie!]
            NetworkTool.shareInstance.request(.GET, urlString: APIBASE, parmas: parma1) { (result, error) in
                if result != nil{
//                    let json = JSON(result!)
//                    print(json)

                    let number = String((result! as? NSDictionary)!["status"]!)
                    if number == "1"{
                        let dic = ((result as? NSDictionary)!["data"])as?NSDictionary
                        let cartArr = dic!["cart"]as!NSArray
                        self.shoppingCount = String(cartArr.count)
                        self.myTableView.reloadData()
                    }
                    
                    
                }else{
                    SVProgressHUD.showErrorWithStatus("get shopping count error:" + String(error))
                    print("get shopping count error:" + String(error))
                }
            }
            
            
            
            
            //        wishlist
            
            let parma2 = ["main_page":"my_wishlist","zendid":UserSession.shareInstance.cookie!]
            NetworkTool.shareInstance.request(.GET, urlString: APIBASE, parmas: parma2) { (result, error) in
                if result != nil{
//                    let json = JSON(result!)
//                    print(json)

                    let number = String((result! as? NSDictionary)!["status"]!)
                    if number == "1"{
                        let cartArr = ((result as? NSDictionary)!["data"])as!NSArray
                        self.wishListCount = String(cartArr.count)
                        self.myTableView.reloadData()
                    }
                    
                    
                }else{
                    SVProgressHUD.showErrorWithStatus("get wishlist count error:" + String(error))
                    print("get wishlist count error:" + String(error))
                }
            }

            
            
            //        order
            
            let urlStr = APIBASE + "main_page=account_history"
            
            let parma3 = ["current_page_number":"1","zendid":UserSession.shareInstance.cookie!]
            NetworkTool.shareInstance.request(.POST, urlString: urlStr, parmas: parma3, finishedBlock: { (result, error) in
                if result != nil{
//                    let json = JSON(result!)
//                    print(json)
                    let number = String((result! as? NSDictionary)!["status"]!)
                    if number == "1"{
                    let dic = ((result as? NSDictionary)!["data"])as?NSDictionary
                    let cartArr = dic!["order_history"]as!NSArray
                    self.orderCount = String(cartArr.count)
                    self.myTableView.reloadData()

                }
                    
                }else{
                    SVProgressHUD.showErrorWithStatus("get order count error:" + String(error))
                    print("get order count error:" + String(error))
                }

            })
    }
    }

    
}


extension RightSideViewController{
    
    private func creatTableView(){
        myTableView.delegate = self
        myTableView.dataSource = self
        myTableView.backgroundColor = UIColor.whiteColor()
        self.view.addSubview(myTableView)
        myTableView.registerClass(RightTableViewCell.self, forCellReuseIdentifier: RIGHTCELL)
        
        
    }
    
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 9
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(RIGHTCELL)
        cell?.selectionStyle = .None
        (cell as? RightTableViewCell)?.myImgView.image = UIImage(named: self.imageViewArray[indexPath.row])
        (cell as? RightTableViewCell)?.titleLabel.text = self.titleArray[indexPath.row]
        
        if indexPath.row == 0 {
            if Int(shoppingCount)! > 0 {
                shoppongCountLabel.text = shoppingCount
                (cell as? RightTableViewCell)?.addSubview(shoppongCountLabel)
            }else{
                    shoppongCountLabel.removeFromSuperview()
            }
        }
        
        
        if indexPath.row == 1 {
            if Int(wishListCount)! > 0 {
                wishlistCountLabel.text = wishListCount
                (cell as? RightTableViewCell)?.addSubview(wishlistCountLabel)
            }else{
                    wishlistCountLabel.removeFromSuperview()
            }
        }
        
        if indexPath.row == 2 {
            if Int(orderCount)! > 0 {
                orderCountLabel.text = orderCount
                (cell as? RightTableViewCell)?.addSubview(orderCountLabel)
            }else{
                    orderCountLabel.removeFromSuperview()
            }
        }
        
        
        return cell!
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return SCREEN_HEIGHT * 0.2
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.row == 0{
            let nav = UINavigationController(rootViewController: ShoppingCarViewController())
            self.presentViewController(nav, animated: true, completion: {
                
            })
        }
        if indexPath.row == 1 {
            let nav = UINavigationController(rootViewController: WishListViewController())
            self.presentViewController(nav, animated: true, completion: {
                
            })
        }
        if indexPath.row == 2 {
            let nav = UINavigationController(rootViewController: OrderViewController())
            self.presentViewController(nav, animated: true, completion: {
                
            })
        }
        if indexPath.row == 3 {
            let nav = UINavigationController(rootViewController: CurrencyViewController())
            self.presentViewController(nav, animated: true, completion: {
                
            })
        }
        if indexPath.row == 4 {
            let nav = UINavigationController(rootViewController: ContactViewController())
            self.presentViewController(nav, animated: true, completion: {
                
            })
        }
        if indexPath.row == 5 {
            let nav = UINavigationController(rootViewController: ReturnViewController())
            self.presentViewController(nav, animated: true, completion: {
                
            })
        }
        if indexPath.row == 6 {
            let nav = UINavigationController(rootViewController: PrivacyStatementViewController())
            self.presentViewController(nav, animated: true, completion: {
                
            })
        }
        if indexPath.row == 7 {
            let nav = UINavigationController(rootViewController: PricvacyViewController())
            self.presentViewController(nav, animated: true, completion: {
                
            })
        }
        if indexPath.row == 8 {
            if UserSession.shareInstance.isLogin == true {
                UserSession.shareInstance.isLogin = false
                UserSession.shareInstance.email = ""
                UserSession.shareInstance.cookie = ""
                shoppingCount = "0"
                wishListCount = "0"
                orderCount = "0"
                let parma = ["main_page":"logoff"]
                NetworkTool.shareInstance.request(.GET, urlString: APIBASE, parmas: parma, finishedBlock: { (result, error) in
                    if result != nil{
                        SVProgressHUD.showSuccessWithStatus("login out success!")
                    }else{
                        SVProgressHUD.showErrorWithStatus("logoff error:"+String(error))
                    }
                })
                tableView.reloadData()
                
                let center = NSNotificationCenter.defaultCenter()
                let notification = NSNotification(name: "letHomePageToRefresh", object: self, userInfo: nil)
                center.postNotification(notification)
                
            }else{
                SVProgressHUD.showInfoWithStatus("You have not logged in!")
            }
        }
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return SCREEN_HEIGHT * 0.08
    }
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.frame = CGRectMake(0, 0, SCREEN_WIDTH*0.75, SCREEN_HEIGHT*0.2)
        view.backgroundColor = UIColor.whiteColor()
        let iconImageView = UIImageView()
        iconImageView.frame = CGRectMake(SCREEN_WIDTH*0.75/2-SCREEN_HEIGHT*0.05, 20, SCREEN_HEIGHT*0.1, SCREEN_HEIGHT*0.1)
        iconImageView.image = UIImage(named: "img_touxiang")
        view.addSubview(iconImageView)
        
        let emailStr = UserSession.shareInstance.email
        
        let emailLabel = UILabel()
        emailLabel.frame = CGRectMake(0, 30+SCREEN_HEIGHT*0.1, SCREEN_WIDTH*0.75, SCREEN_HEIGHT*0.1-40)
        emailLabel.textAlignment = .Center
        emailLabel.font = UIFont.systemFontOfSize(14)
        if emailStr == nil || emailStr == "" {
            emailLabel.text = "LOGIN/SIGN IN"
        }else{
            emailLabel.textColor = UIColor.grayColor()
            emailLabel.text = emailStr
        }
        view.addSubview(emailLabel)
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(headerViewTap))
        view.addGestureRecognizer(tap)
        
        
        return view
        
    }
    
    
    func headerViewTap(){
        let isLogin = UserSession.shareInstance.isLogin
        if isLogin == true {
            SVProgressHUD.showInfoWithStatus("You have landed, don't need to register！")
//            SVProgressHUD.showWithStatus("You have landed, don't need to register！")
        }else{
            let loginVC = LoginViewController()
            loginVC.delegate = self
            let nav = UINavigationController(rootViewController: loginVC)
            
            self.presentViewController(nav, animated: true) {
                
            }
        }
        
        
    }
    
    func letRightVCRefresh() {
        
        self.getCountData()
        
        self.myTableView.reloadData()
    }
    
}

















